package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.Users;
import com.zhentao.pojo.Students;
import com.zhentao.pojo.Teachers;
import com.zhentao.service.StudentsService;
import com.zhentao.service.TeachersService;
import com.zhentao.service.UsersService;
import com.zhentao.service.StudentCoursesService;
import com.zhentao.service.TeacherEarningsService;
import com.zhentao.service.LiveRoomsService;
import com.zhentao.service.AssignmentSubmissionsService;
import com.zhentao.service.CoursesService;
import com.zhentao.service.AssignmentsService;
import com.zhentao.pojo.Courses;
import com.zhentao.pojo.Assignments;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import java.util.List;
import java.math.BigDecimal;
import java.util.Calendar;

/**
 * 登录控制器
 * 支持学员和讲师两种登录方式
 */
@RestController
@RequestMapping("login")
public class LoginController {
    @Autowired
    UsersService usersService;
    @Autowired
    TeachersService teachersService;
    @Autowired
    StudentsService studentsService;
    @Autowired
    StudentCoursesService studentCoursesService;
    @Autowired
    TeacherEarningsService teacherEarningsService;
    @Autowired
    LiveRoomsService liveRoomsService;
    @Autowired
    AssignmentSubmissionsService assignmentSubmissionsService;
    @Autowired
    CoursesService coursesService;
    @Autowired
    AssignmentsService assignmentsService;
    
    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    // MinIO配置 - 头像URL前缀
    private static final String MINIO_AVATAR_PREFIX = "http://49.232.48.2:9000/avatar/";
    
    /**
     * 处理头像URL，如果是相对路径则拼接MinIO地址
     */
    private String processAvatarUrl(String avatarUrl) {
        if (avatarUrl == null || avatarUrl.trim().isEmpty()) {
            return null;
        }
        // 如果已经是完整URL，直接返回
        if (avatarUrl.startsWith("http://") || avatarUrl.startsWith("https://")) {
            return avatarUrl;
        }
        // 如果是相对路径，拼接MinIO地址
        return MINIO_AVATAR_PREFIX + avatarUrl;
    }
    
    /**
     * 将讲师等级转换为中文显示
     */
    private String translateTeacherLevel(Object teacherLevel) {
        if (teacherLevel == null) {
            return null;
        }
        String level = teacherLevel.toString();
        switch (level) {
            case "junior":
                return "初级讲师";
            case "intermediate":
                return "中级讲师";
            case "senior":
                return "高级讲师";
            default:
                return level;
        }
    }
    
    /**
     * 用户名密码登录
     * 支持学员和讲师通用登录，自动识别用户类型
     * @param request 登录请求参数，包含username(用户名/邮箱/手机号)、password(密码)、userType(可选，用于前端区分按钮)
     * @return 登录结果，包含用户基本信息和对应的学员/讲师详细信息
     */
    @PostMapping("/password")
    public ResponseEntity<Map<String, Object>> loginByPassword(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String loginName = request.get("username"); // 可以是用户名、邮箱或手机号
            String password = request.get("password");
            String userType = request.get("userType"); // 可选参数，如果传入则验证匹配
            
            // 参数校验
            if (loginName == null || loginName.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "登录名不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (password == null || password.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 查找用户（支持用户名、邮箱、手机号登录）
            QueryWrapper<Users> query = new QueryWrapper<>();
            query.and(wrapper -> wrapper
                .eq("username", loginName)
                .or()
                .eq("email", loginName)
                .or()
                .eq("phone", loginName)
            );
            
            Users user = usersService.getOne(query);
            
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 如果传入了userType参数，则验证是否匹配（可选验证）
            String dbUserType = user.getUserType() != null ? user.getUserType().toString().toLowerCase() : "";
            if (userType != null && !userType.trim().isEmpty()) {
                // 验证传入的用户类型是否有效
                if (!"student".equalsIgnoreCase(userType) && !"teacher".equalsIgnoreCase(userType)) {
                    response.put("success", false);
                    response.put("message", "用户类型无效，必须为student(学员)或teacher(讲师)");
                    return ResponseEntity.badRequest().body(response);
                }
                // 验证用户类型是否匹配（可选验证，如果前端传入了userType则验证）
                if (!userType.equalsIgnoreCase(dbUserType)) {
                    response.put("success", false);
                    response.put("message", "用户类型不匹配，请选择正确的登录方式");
                    return ResponseEntity.badRequest().body(response);
                }
            }
            
            // 如果数据库中没有用户类型，返回错误
            if (dbUserType.isEmpty() || (!dbUserType.equals("student") && !dbUserType.equals("teacher"))) {
                response.put("success", false);
                response.put("message", "用户类型无效，请联系管理员");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证密码（支持BCrypt加密和明文密码的向后兼容）
            String storedPasswordHash = user.getPasswordHash();
            boolean passwordValid = false;
            boolean isPlainText = false;
            
            // 判断密码是否为BCrypt格式（BCrypt密码通常以 $2a$, $2b$, $2y$ 开头）
            if (storedPasswordHash != null && 
                (storedPasswordHash.startsWith("$2a$") || 
                 storedPasswordHash.startsWith("$2b$") || 
                 storedPasswordHash.startsWith("$2y$"))) {
                // 使用BCrypt验证加密密码
                try {
                    passwordValid = passwordEncoder.matches(password, storedPasswordHash);
                } catch (Exception e) {
                    // BCrypt验证失败，可能是格式不正确
                    passwordValid = false;
                }
            } else {
                // 明文密码（向后兼容旧数据）
                isPlainText = true;
                passwordValid = password.equals(storedPasswordHash);
            }
            
            if (!passwordValid) {
                response.put("success", false);
                response.put("message", "密码错误");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 如果使用的是明文密码且验证成功，自动将密码加密并更新到数据库
            if (isPlainText) {
                try {
                    String encryptedPassword = passwordEncoder.encode(password);
                    user.setPasswordHash(encryptedPassword);
                    user.setUpdatedAt(new Date());
                    usersService.updateById(user);
                    // 记录日志提示密码已加密（可选）
                    System.out.println("用户 " + user.getUsername() + " 的明文密码已自动加密并更新到数据库");
                } catch (Exception e) {
                    // 更新失败不影响登录，只记录错误
                    System.err.println("自动加密密码失败: " + e.getMessage());
                }
            }
            
            // 登录成功，返回用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            userInfo.put("phone", user.getPhone());
            userInfo.put("realName", user.getRealName());
            userInfo.put("avatarUrl", processAvatarUrl(user.getAvatarUrl())); // 处理头像URL
            userInfo.put("userType", user.getUserType());
            userInfo.put("createdAt", user.getCreatedAt());
            
            // 根据数据库中的用户类型自动查询详细信息
            Map<String, Object> detailInfo = null;
            if ("student".equalsIgnoreCase(dbUserType)) {
                // 查询学员详细信息
                QueryWrapper<Students> studentQuery = new QueryWrapper<>();
                studentQuery.eq("user_id", user.getId());
                Students student = studentsService.getOne(studentQuery);
                
                if (student != null) {
                    detailInfo = new HashMap<>();
                    detailInfo.put("id", student.getId());
                    detailInfo.put("userId", student.getUserId());
                    detailInfo.put("gradeLevel", student.getGradeLevel());
                    detailInfo.put("schoolName", student.getSchoolName());
                    detailInfo.put("balance", student.getBalance());
                }
            } else if ("teacher".equalsIgnoreCase(dbUserType)) {
                // 查询讲师详细信息
                QueryWrapper<Teachers> teacherQuery = new QueryWrapper<>();
                teacherQuery.eq("user_id", user.getId());
                Teachers teacher = teachersService.getOne(teacherQuery);
                
                if (teacher != null) {
                    detailInfo = new HashMap<>();
                    detailInfo.put("id", teacher.getId());
                    detailInfo.put("userId", teacher.getUserId());
                    detailInfo.put("teacherLevel", translateTeacherLevel(teacher.getTeacherLevel())); // 转换为中文
                    detailInfo.put("introduction", teacher.getIntroduction());
                    detailInfo.put("hourlyRate", teacher.getHourlyRate());
                    detailInfo.put("isVerified", teacher.getIsVerified());
                }
            }
            
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("user", userInfo);
            response.put("detail", detailInfo); // 学员或讲师的详细信息
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 手机号验证码登录
     * TODO: 待实现
     * @param request 登录请求参数，包含phone(手机号)、code(验证码)、userType(用户类型: student/teacher)
     * @return 登录结果
     */
    @PostMapping("/sms")
    public ResponseEntity<Map<String, Object>> loginBySms(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        // TODO: 实现手机号验证码登录逻辑
        // 1. 验证手机号格式
        // 2. 验证验证码是否正确（需要集成短信验证码服务）
        // 3. 根据userType查找对应的用户
        // 4. 返回用户信息和详细信息
        
        response.put("success", false);
        response.put("message", "手机号验证码登录功能暂未实现");
        return ResponseEntity.status(501).body(response); // 501 Not Implemented
    }
    
    /**
     * 获取讲师中心信息
     * 包含讲师基本信息、统计数据（学员总数、总收益、今日课程、待处理事项等）
     * @param userId 用户ID（登录后获取的user.id）
     * @return 讲师中心完整信息
     */
    @GetMapping("/teacher/info/{userId}")
    public ResponseEntity<Map<String, Object>> getTeacherInfo(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 1. 查询讲师基本信息
            QueryWrapper<Teachers> teacherQuery = new QueryWrapper<>();
            teacherQuery.eq("user_id", userId);
            Teachers teacher = teachersService.getOne(teacherQuery);
            
            if (teacher == null) {
                response.put("success", false);
                response.put("message", "讲师不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 2. 查询用户基本信息
            Users user = usersService.getById(teacher.getUserId());
            
            // 3. 统计学员总数（通过该讲师的所有课程的学员数）
            Long totalStudents = 0L;
            QueryWrapper<Courses> coursesQuery = new QueryWrapper<>();
            coursesQuery.eq("teacher_id", user.getId()); // courses.teacher_id关联users.id
            List<Courses> teacherCourses = coursesService.list(coursesQuery);
            
            if (teacherCourses != null && !teacherCourses.isEmpty()) {
                List<Long> courseIds = teacherCourses.stream()
                    .map(Courses::getId)
                    .collect(java.util.stream.Collectors.toList());
                
                QueryWrapper<com.zhentao.pojo.StudentCourses> studentCoursesQuery = new QueryWrapper<>();
                studentCoursesQuery.in("course_id", courseIds);
                totalStudents = studentCoursesService.count(studentCoursesQuery);
            }
            
            // 4. 统计总收益
            BigDecimal totalRevenue = BigDecimal.ZERO;
            QueryWrapper<com.zhentao.pojo.TeacherEarnings> earningsQuery = new QueryWrapper<>();
            earningsQuery.eq("teacher_id", user.getId()); // teacher_earnings.teacher_id关联users.id
            List<com.zhentao.pojo.TeacherEarnings> earnings = teacherEarningsService.list(earningsQuery);
            
            if (earnings != null) {
                for (com.zhentao.pojo.TeacherEarnings earning : earnings) {
                    if (earning.getEarningAmount() != null) {
                        totalRevenue = totalRevenue.add(earning.getEarningAmount());
                    }
                }
            }
            
            // 5. 统计今日课程数
            int todayCourses = 0;
            Calendar today = Calendar.getInstance();
            today.set(Calendar.HOUR_OF_DAY, 0);
            today.set(Calendar.MINUTE, 0);
            today.set(Calendar.SECOND, 0);
            today.set(Calendar.MILLISECOND, 0);
            
            Date todayStart = today.getTime();
            
            Calendar tomorrow = Calendar.getInstance();
            tomorrow.set(Calendar.HOUR_OF_DAY, 0);
            tomorrow.set(Calendar.MINUTE, 0);
            tomorrow.set(Calendar.SECOND, 0);
            tomorrow.set(Calendar.MILLISECOND, 0);
            tomorrow.add(Calendar.DAY_OF_MONTH, 1);
            
            Date tomorrowStart = tomorrow.getTime();
            
            QueryWrapper<com.zhentao.pojo.LiveRooms> liveRoomsQuery = new QueryWrapper<>();
            liveRoomsQuery.eq("teacher_id", user.getId()); // live_rooms.teacher_id关联users.id
            liveRoomsQuery.ge("start_time", todayStart);
            liveRoomsQuery.lt("start_time", tomorrowStart);
            todayCourses = (int) liveRoomsService.count(liveRoomsQuery);
            
            // 6. 统计待批改作业数
            int pendingHomework = 0;
            if (teacherCourses != null && !teacherCourses.isEmpty()) {
                List<Long> courseIds = teacherCourses.stream()
                    .map(Courses::getId)
                    .collect(java.util.stream.Collectors.toList());
                
                // 获取这些课程的所有作业ID
                QueryWrapper<Assignments> assignmentsQuery = new QueryWrapper<>();
                assignmentsQuery.in("course_id", courseIds);
                List<Assignments> assignments = assignmentsService.list(assignmentsQuery);
                
                if (assignments != null && !assignments.isEmpty()) {
                    List<Long> assignmentIds = assignments.stream()
                        .map(Assignments::getId)
                        .collect(java.util.stream.Collectors.toList());
                    
                    // 统计没有分数的作业提交（待批改）
                    QueryWrapper<com.zhentao.pojo.AssignmentSubmissions> submissionsQuery = new QueryWrapper<>();
                    submissionsQuery.in("assignment_id", assignmentIds);
                    submissionsQuery.isNull("total_score");
                    pendingHomework = (int) assignmentSubmissionsService.count(submissionsQuery);
                }
            }
            
            // 7. 待回复问题数（先返回0，后续补充）
            int pendingQuestions = 0;
            
            // 8. 待审核课程数（状态为"draft"的课程）
            int pendingCourses = 0;
            QueryWrapper<Courses> pendingCoursesQuery = new QueryWrapper<>();
            pendingCoursesQuery.eq("teacher_id", user.getId()); // 使用user.getId()
            pendingCoursesQuery.eq("status", "draft"); // 数据库中是draft不是草稿
            pendingCourses = (int) coursesService.count(pendingCoursesQuery);
            
            // 构建响应数据
            Map<String, Object> teacherInfo = new HashMap<>();
            teacherInfo.put("id", user.getId());
            teacherInfo.put("username", user.getUsername());
            teacherInfo.put("realName", user.getRealName());
            teacherInfo.put("email", user.getEmail());
            teacherInfo.put("phone", user.getPhone());
            teacherInfo.put("avatarUrl", processAvatarUrl(user.getAvatarUrl())); // 处理头像URL
            
            Map<String, Object> teacherDetail = new HashMap<>();
            teacherDetail.put("id", teacher.getId());
            teacherDetail.put("teacherLevel", translateTeacherLevel(teacher.getTeacherLevel())); // 转换为中文
            teacherDetail.put("introduction", teacher.getIntroduction());
            teacherDetail.put("hourlyRate", teacher.getHourlyRate());
            teacherDetail.put("isVerified", teacher.getIsVerified());
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalStudents", totalStudents);
            stats.put("totalRevenue", totalRevenue.doubleValue());
            stats.put("todayCourses", todayCourses);
            
            Map<String, Object> pendingTasks = new HashMap<>();
            pendingTasks.put("homework", pendingHomework);
            pendingTasks.put("questions", pendingQuestions);
            pendingTasks.put("courses", pendingCourses);
            
            Map<String, Object> result = new HashMap<>();
            result.put("teacherInfo", teacherInfo);
            result.put("teacherDetail", teacherDetail);
            result.put("stats", stats);
            result.put("pendingTasks", pendingTasks);
            
            response.put("success", true);
            response.put("message", "获取成功");
            response.put("data", result);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }
    
}
